package com.langxin.erp.action.upload;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.langxin.erp.util.constant.DateEnum;
import com.langxin.erp.util.constant.SiteConstant;
import com.langxin.erp.util.web.DateUtils;
import com.langxin.erp.util.web.JsonUtils;

/**
 * 上传文件
 * @author gu
 *
 */
@Controller
public class UploadAction {

	/**
	 * 上传文件
	 * @param resp
	 */
	@RequestMapping(value="/upload",method={RequestMethod.POST})
	@ResponseBody
	public String upload(HttpServletResponse resp, MultipartFile uploadFile){
		if(uploadFile == null){
			return null;
		}
		
		// 图片从存放目录 [年月]
		String path = SiteConstant.UPLOAD_FILE_PATH + "/" + DateUtils.parseDate(new Date(), DateEnum.UNSIGNED_DATE);
		File mk = new File(path);
		if(!mk.exists()){
			mk.mkdir();
		}
		String fileName = uploadFile.getOriginalFilename();
		String suffix = fileName.substring(fileName.lastIndexOf("."));
		// 图片名字
		String newFileName = UUID.randomUUID() + suffix;
		File file = new File(path + "/" + newFileName);
		try {
			uploadFile.transferTo(file);
		} catch (IllegalStateException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		String url =  SiteConstant.UPLOAD_FILE_URL + DateUtils.parseDate(new Date(), DateEnum.UNSIGNED_DATE) + "/" + newFileName;
		Map<String, String> rs = new HashMap<String, String>();
		rs.put("success", "true");
		rs.put("url", url);
		return JsonUtils.toJson(rs);
	}
}
